package com.zhihui.client.alarm.controller;

import com.aliyun.oss.OSSClient;
import com.zhihui.client.alarm.common.JsonData;
import com.zhihui.client.alarm.oss.OSSClientConstants;
import com.zhihui.client.alarm.util.AliyunOSSClientUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 图片controller
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(value = "PhotoController",description = "上传照片controller")
public class PhotoController {

    //文件上传相关代码
    @PostMapping(value = "/upload")
    public JsonData upload(@RequestParam("file")MultipartFile file) {

//        获取oss 服务器地址
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();

        if (file.isEmpty()) {
            return JsonData.fail("文件为空");
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        // 文件上传后的路径

        /**
         * 通过临时文件转换类型
         */
        File f = null;
        try {
            f=File.createTempFile(fileName, suffixName);
            file.transferTo(f);
            f.deleteOnExit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
          String Md5Kay=  AliyunOSSClientUtil.uploadObject2OSS(ossClient,f, OSSClientConstants.BACKET_NAME,OSSClientConstants.FOLDER );
            return JsonData.success(Md5Kay,"上传成功，文件名为：");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return JsonData.fail("上传失败");
    }
}
